package cn.com.woxitech.dev.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.pili.API;
import com.pili.Hub;
import com.pili.PiliException;
import com.pili.Stream;
import com.pili.Stream.SaveAsResponse;
import com.pili.Stream.Status;
import com.qiniu.Credentials;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;

import cn.com.woxitech.dev.common.APIResult;
import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.model.ImageInfo;
import cn.com.woxitech.dev.model.UpToken;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;

@RestController
@RequestMapping(value = "/qiniu")
public class QiNiuController {
	private final static Logger logger = Logger.getLogger(QiNiuController.class);

	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	
	@Autowired
	QiniuService qiniuService;
	
	@RequestMapping(value = "/uploadtoken/{key}")
	public UpToken getUploadTokenByKey(@PathVariable String key) {
		logger.info("getUploadToken by key:"+key);
		Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
		String uploadToken = auth.uploadToken("haojsqiniu", key);
		
		logger.info("uploadToken:"+uploadToken);
		return APIResultFactory.upToken(uploadToken);
	}
	
	@RequestMapping(value = "/uploadtoken")
	public UpToken getUploadToken() {
		logger.info("getUploadToken");
		Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
		String uploadToken = auth.uploadToken("haojsqiniu");
		return APIResultFactory.upToken(uploadToken);
	}

	@RequestMapping(value = "/imageInfo", method = RequestMethod.POST)
	public APIResult getImageInfo(@RequestBody String body) {
		logger.info("getImageInfo");
		try {
			ImageInfo o = new ImageInfo();
			JsonNode jsonNode = JSONUtils.toJson(body);
			String url = jsonNode.get("url").asText();
			String resp = HttpClientUtils.sendGET(url + "?imageInfo");

			JsonNode _resp = JSONUtils.toJson(resp);
			o.setColorModel(_resp.get("colorModel").asText());
			o.setFormat(_resp.get("format").asText());
			o.setHeight(_resp.get("height").asInt());
			o.setWidth(_resp.get("width").asInt());

			return APIResultFactory.success(o);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}

	}

	@RequestMapping(value = "/stream_create", method = RequestMethod.POST)
	public Object createStream(@RequestBody String body) {
		// Instantiate an Hub object
		Credentials credentials = new Credentials(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY); // Credentials
																									// Object
		Hub hub = new Hub(credentials, Const.QINIU_HUB_NAME);
		// Create a new Stream
		String title = null; // optional, auto-generated as default
		String publishKey = null; // optional, auto-generated as default
		String publishSecurity = null; // optional, can be "dynamic" or
										// "static", "dynamic" as default
		Stream stream = null;
		try {
			stream = hub.createStream(title, publishKey, publishSecurity);
			System.out.println("hub.createStream:");
			System.out.println(stream.toJsonString());
			String originUrl = stream.rtmpLiveUrls().get(Stream.ORIGIN);
			System.out.println("Stream rtmpLiveUrls()");
			System.out.println(originUrl);
			String originLiveHlsUrl = stream.hlsLiveUrls().get(Stream.ORIGIN);
			System.out.println("Stream hlsLiveUrls()");
			System.out.println(originLiveHlsUrl);
			/*
			 * { "id":"z1.test-hub.55d97350eb6f92638c00000a",
			 * "createdAt":"2015-08-22T04:54:13.539Z",
			 * "updatedAt":"2015-08-22T04:54:13.539Z",
			 * "title":"55d97350eb6f92638c00000a", "hub":"test-hub",
			 * "disabled":false, "publishKey":"ca11e07f094c3a6e",
			 * "publishSecurity":"dynamic", "hosts":{ "publish":{
			 * "rtmp":"ey636h.publish.z1.pili.qiniup.com" }, "live":{
			 * "hdl":"ey636h.live1-hdl.z1.pili.qiniucdn.com",
			 * "hls":"ey636h.live1-hls.z1.pili.qiniucdn.com",
			 * "rtmp":"ey636h.live1-rtmp.z1.pili.qiniucdn.com" }, "playback":{
			 * "hls":"ey636h.playback1.z1.pili.qiniucdn.com" } } }
			 */
		} catch (PiliException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		return APIResultFactory.success();
	}

	@RequestMapping(value = "/stream_save", method = RequestMethod.POST)
	public Object saveStream(@RequestBody String body) {
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
//			
//			String roomuuid = null;
//			if( jsonNode.get("roomuuid") != null){
//				roomuuid = jsonNode.get("roomuuid").asText(); 
//			}
//
//			String coverurl = null;
//			if( jsonNode.get("coverurl") != null){
//				coverurl = jsonNode.get("coverurl").asText(); 
//			}
//			//更新封面
//			if(roomuuid != null){
//				WmRoom room = roomService.getRoomsByUuid(roomuuid);
//				room.setCoverurl(coverurl);
//				room.setLivecoverurl(coverurl);
//				roomService.updateByPrimaryKeyHard(room);
//			}

			
			String streamId = jsonNode.get("streamId").asText();
			long saveAsStart = jsonNode.get("saveAsStart").asLong(); // 开始时间
			long saveAsEnd = jsonNode.get("saveAsEnd").asLong(); // 结束时间
			// Instantiate an Hub object
			Credentials credentials = new Credentials(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY); // Credentials
																										// Object
			Hub hub = new Hub(credentials, Const.QINIU_HUB_NAME);
			Stream stream = hub.getStream(streamId);
			String videoName = saveAsStart+"_"+saveAsEnd;
			System.out.println(stream.toJsonString());
			// Save Stream as a file
			String saveAsFormat = "m3u8"; // required
			String saveAsName = videoName + "." + saveAsFormat; // required
			
			// String saveAsNotifyUrl = null; // optional
			SaveAsResponse response = stream.saveAs(saveAsName, saveAsFormat, saveAsStart, saveAsEnd);
			
			System.out.println("Stream saveAs()");
			System.out.println(response.toString());
			/*
			 * { "url":
			 * "http://ey636h.vod1.z1.pili.qiniucdn.com/recordings/z1.test-hub.55d81a72e3ba5723280000ec/videoName.m3u8",
			 * "targetUrl":
			 * "http://ey636h.vod1.z1.pili.qiniucdn.com/recordings/z1.test-hub.55d81a72e3ba5723280000ec/videoName.mp4",
			 * "persistentId":"z1.55d81c6c7823de5a49ad77b3" }
			 */
			
			return APIResultFactory.success(response.getTargetUrl());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	

	@RequestMapping(value = "/upload_img", method = RequestMethod.POST)
	public APIResult uploadImgToQiniu(@RequestParam("file") MultipartFile file) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			byte[] bytes = file.getBytes();
			String filename = "appimg_" + UUID.randomUUID().toString()+".jpg";
			// 密钥配置
			Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
			String bucket = Const.Bucket_HAOJSQINIU;
			// 创建上传对象
			UploadManager uploadManager = new UploadManager();
			
			String uploadToken = auth.uploadToken(bucket);
			
			uploadManager.put(bytes, filename, uploadToken);
			
			mp.put("url", Const.QINIU_BASE_URL + "/" + filename);
			mp.put("key", filename);
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}

	@RequestMapping(value = "/upload_audio", method = RequestMethod.POST)
	public APIResult uploadAudioToQiniu(@RequestParam("file") MultipartFile file) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			byte[] bytes = file.getBytes();
			String filename = "app" + UUID.randomUUID().toString();
			// 密钥配置
			Auth auth = Auth.create(Const.QINIU_ACCESS_KEY, Const.QINIU_SECRET_KEY);
			String bucket = Const.Bucket_WMHISTORY;
			// 创建上传对象
			UploadManager uploadManager = new UploadManager();
			// 设置转码操作参数
			String fops = "avthumb/mp3/acodec/libmp3lame";
			// 设置转码的队列
			String pipeline = Const.PIPELINE_NAME;
			String urlbase64 = UrlSafeBase64.encodeToString(bucket + ":" + filename + ".mp3");
			String pfops = fops + "|saveas/" + urlbase64;
			// 简单上传，使用默认策略，只需要设置上传的空间名就可以了
			String token = getUpToken(auth, bucket, pfops, pipeline);
			// String token = auth.uploadToken(HJSConstants.Bucket_WMHISTORY);
			// 调用put方法上传
			Response res = uploadManager.put(bytes, filename + ".amr", token);

			// Response res = uploadManager.put(FilePath, null, token);
			// 打印返回的信息
			
			mp.put("playurl", Const.QINIU_CHAT_BASE_URL + "/" + filename);
			mp.put("key", filename);
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}

	public static String getUpToken(Auth auth, String bucketname, String pfops, String pipeline) {
		return auth.uploadToken(bucketname, null, 3600,
				new StringMap().putNotEmpty("persistentOps", pfops).putNotEmpty("persistentPipeline", pipeline), true);
	}
	
	
	@RequestMapping(value = "/test")
	public Object test(@RequestBody String body) {
		
		String streamid = "";//"z1.haojslive.57cf97f6b1d1ff829c047712";
		
		try {
			if(!body.equals("")){
				streamid = body; 
			}

			Map<String, String> mp = qiniuService.getStreamUrlsByStreamId(streamid);
			System.out.println(qiniuService.getStreamStatus(streamid));
			System.out.println(mp.get("json"));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		qiniuService.getStreamStatus("z1.haojslive.57cf97f6b1d1ff829c047712");
//		String publishurl = qiniuService.generatePublishUrl();
		
//		try {
//			
//			streamid = "aaa";
//			String url = qiniuService.getSnapshotImg(streamid);
//			
//			System.out.println(url);
//			
//		} catch (PiliException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			
//			if(e.getMessage().equals("Not Found")){
//				//
//				
//			}
//		}
//		try {
//			Map<String ,Object> mp = qiniuService.createQiniuStream();
//		} catch (PiliException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}	
//		int s = qiniuService.getStreamStatus(streamid);
		
		return "";
	}
}
